package com.yocard.yxyd.base;


import com.yocard.yxyd.http.HttpManager;
import com.yocard.yxyd.http.model.base.Response;
import com.yocard.yxyd.http.model.response.CommonBean;
import com.yocard.yxyd.ui.activity.LoginActivity;
import com.yocard.yxyd.utils.RxUtil;
import com.yocard.yxyd.utils.util.ActivityUtils;
import com.yocard.yxyd.utils.util.CacheDoubleStaticUtils;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public class RxPresenter<T extends BaseView> implements BasePresenter<T> {
    protected HttpManager httpManager;

    public RxPresenter(HttpManager manager){
        httpManager = manager;
    }

    protected T mView;
    protected CompositeDisposable mCompositeDisposable;

    protected void unSubscribe() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }
    }

    protected void addSubscribe(Disposable subscription) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(subscription);
    }

//    protected <U> void addRxBusSubscribe(Class<U> eventType, Consumer<U> act) {
//        if (mCompositeDisposable == null) {
//            mCompositeDisposable = new CompositeDisposable();
//        }
//        mCompositeDisposable.add(RxBus.getDefault().toDefaultFlowable(eventType, act));
//    }

    @Override
    public void attachView(T view) {
        this.mView = view;
    }

    @Override
    public void detachView() {
        this.mView = null;
        unSubscribe();
    }

    public void refreshToken(){
        addSubscribe(httpManager.refreshToken()
                .compose(RxUtil.rxSchedulerHelper())
                .subscribeWith(new CommonSubscriber<CommonBean>(mView) {

                    @Override
                    public void onNext(Response<CommonBean> tResponse) {
                        if (tResponse.getCode() == Constants.STATUS_LOGIN_MUTI) {
                            mView.showErrorMsg("登录已失效，请重新登录");
                            CacheDoubleStaticUtils.remove(Constants.KEY_TOKEN);
                            ActivityUtils.startActivity(LoginActivity.class);
                            return;
                        }
                        super.onNext(tResponse);
                    }

                    @Override
                    public void onSuccess(CommonBean data) {
                        CacheDoubleStaticUtils.put(Constants.KEY_TOKEN, data.getAccess_token());
                    }

                }));
    }
}
